package org.dromara.system.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * 卡号校验工具类
 */
public class CardValidUtils {

    // 校验卡号
    public static String validateCardNumber(String value) {
        value = value.replaceAll(" ", "");
        if (!Pattern.matches("^\\d{13,19}$", value)) {
            return "Invalid Card Number Char.";
        }

        int sum = 0;
        boolean alt = false;

        for (int i = value.length() - 1; i >= 0; i--) {
            int n = Character.getNumericValue(value.charAt(i));
            if (alt) {
                n *= 2;
                if (n > 9) {
                    n -= 9;
                }
            }
            sum += n;
            alt = !alt;
        }

        if (sum % 10 != 0) {
            return "Invalid Card Number.";
        }

        return "";
    }

    // 校验有效期
    public static String validateCardExpiry(String value) {
        String[] arr = value.replaceAll(" ", "").split("/");
        if (arr.length != 2) {
            return "Invalid Card Expiry Char.";
        }

        String month = arr[0];
        String year = arr[1];

        if (!Pattern.matches("^\\d{2}$", month) || !Pattern.matches("^\\d{2}$", year)) {
            return "Invalid Card Expiry Month / Year.";
        }

        int intMonth = Integer.parseInt(month);
        int intYear = Integer.parseInt(year);

        if (intMonth < 1 || intMonth > 12) {
            return "Invalid Card Expiry Month.";
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yy/MM");
        String currentDate = new SimpleDateFormat("yy/MM").format(new Date());
        try {
            Date cardExpiryDate = sdf.parse(year + "/" + month);
            Date currentDateObj = sdf.parse(currentDate);

            if (cardExpiryDate.before(currentDateObj)) {
                return "Invalid Card Expiry Date.";
            }
        } catch (ParseException e) {
            // This should not happen due to the regex checks above
            e.printStackTrace();
            return "Error parsing date.";
        }

        return "";
    }

    // 校验CVC
    public static String validateCardCVC(String value) {
        if (!Pattern.matches("^\\d{3,4}$", value)) {
            return "Invalid Card CVC.";
        }

        return "";
    }

    // 示例使用（主方法）
    public static void main(String[] args) {
        System.out.println(validateCardNumber("123456789012345")); // 示例卡号
        System.out.println(validateCardExpiry("12/25")); // 示例有效期
        System.out.println(validateCardCVC("123")); // 示例CVC
    }
}
